package com.qijian.framework.web.service;

import com.qijian.common.constant.Constants;
import com.qijian.common.core.domain.UserSalaryData;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.core.domain.model.LoginUser;
import com.qijian.common.core.redis.RedisCache;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.exception.user.*;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.MessageUtils;
import com.qijian.common.utils.ServletUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.ip.IpUtils;
import com.qijian.framework.manager.AsyncManager;
import com.qijian.framework.manager.factory.AsyncFactory;
import com.qijian.framework.security.noPassLogin.NoPassLoginAuthenticationToken;
import com.qijian.framework.security.qywx.QyWxAuthenticationToken;
import com.qijian.system.domain.UserExtra;
import com.qijian.system.service.ISysConfigService;
import com.qijian.system.service.ISysUserService;
import com.qijian.system.service.IUserExtraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author qijian
 */
@Component
@EnableAsync
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;


    @Autowired
    private IUserExtraService userExtraService;

    @Autowired
    private ISysConfigService configService;

    //    @Value("${system.config.captcha}")
//    private boolean captcha;
//
//    @Value("${spring.profiles.active}")
//    private String env;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public SysLoginService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public LoginUser login(String username, String password, String code, String uuid, String clientId) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
//        if (env.equals("druid") && captcha){
//            if (captchaOnOff) {
//                validateCaptcha(username, code, uuid);
//            }
//        }
//        if (env.equals("pre") && captcha){
//            if (captchaOnOff) {
//                validateCaptcha(username, code, uuid);
//            }
//        }
//        if(env.equals("prod")) {
//            if (captchaOnOff) {
//                validateCaptcha(username, code, uuid);
//            }
//        }
        boolean b = tryLogin(username);
        if (!b) {
            throw new RuntimeException("60s内请求太过频繁，请稍后请求登录！");
        }
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        recordLoginInfo(loginUser.getUser());
        //TODO 登录锁表,暂时去掉更新记录
//        recordLoginInfo(loginUser.getUserId());
        userExtraService.recordLoginInfo(loginUser.getUserId(), clientId, IpUtils.getIpAddr(ServletUtils.getRequest()));
        return loginUser;
    }


    /**
     * 企业微信 用户id 换token
     *
     * @param wxUserId
     * @param uuid
     * @return
     */
    public LoginUser QyWxLogin(String wxUserId, String uuid) {

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new QyWxAuthenticationToken(wxUserId));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUserId, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUserId, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(wxUserId, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //recordLoginInfo(loginUser.getUserId());
        return loginUser;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
//        // 密码如果不在指定范围内 错误
//        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//            throw new UserPasswordNotMatchException();
//        }
//        // 用户名不在指定范围内 错误
//        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
//                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
//        {
//            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
//            throw new UserPasswordNotMatchException();
//        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     */
    @Async
    public void recordLoginInfo(Long userId, String clientId) {
        String flag = configService.selectConfigByKey("system.enableRecordLoginInfo");

        if (null == flag || "N".equals(flag)) {
            return;
        }

        System.out.println("SS " + DateUtils.now());

        Random random = new Random();
        try {
            int randomMillis = random.nextInt(5000);
            TimeUnit.MILLISECONDS.sleep(randomMillis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 重置中断状态
        }
        System.out.println("EE " + DateUtils.now());

        UserExtra userExtra = new UserExtra();
        userExtra.setUserId(userId);
        userExtra.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        userExtra.setLastLoginTime(DateUtils.dateTimeNow());
        userExtra.setLoginDate(DateUtils.getNowDate());
        if (StringUtils.isNotEmpty(clientId)) {
            userExtra.setClientId(clientId);
        }
        userExtraService.saveOrUpdate(userExtra);

        if (StringUtils.isNotEmpty(clientId)) {
            // if multiple users share the  same client  set others to null
            userExtraService.resetClientId(userId, clientId);
        }
    }

    public boolean tryLogin(String username) {
        String key = "login:limit:" + username;
        long count = redisTemplate.opsForValue().increment(key, 1);
        if (count == 1) {
            redisTemplate.expire(key, 60, TimeUnit.SECONDS); // 60秒内限制
        }
        if (count > 5) { // 60秒内最多允许5次登录请求
            return false;
        }
        // 处理登录逻辑
        return true;
    }

    /**
     * 无密码的登录验证
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @param clientId
     * @return
     */
    public LoginUser noPasswordLogin(String username, String code, String uuid, String clientId) {
        boolean b = tryLogin(username);
        if (!b) {
            throw new RuntimeException("60s内请求太过频繁，请稍后请求登录！");
        }
        //登录前置校验
        noPasswordLoginPreCheck(username);

        SysUser sysUser = userService.selectUserByUserName(username);
        LoginUser tokenLoginUser = new LoginUser();
        tokenLoginUser.setUser(sysUser);
        // 用户验证
        Authentication authentication = null;
        //直接生成认证对象（跳过密码验证）
        authentication =   authenticationManager.authenticate(new NoPassLoginAuthenticationToken(username));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        userExtraService.recordLoginInfo(loginUser.getUserId(), clientId, IpUtils.getIpAddr(ServletUtils.getRequest()));
        return loginUser;
    }

    /**
     * 登录前置校验
     * @param username 用户名
     */
    private void noPasswordLoginPreCheck(String username) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    public List<SysUser> getAllUser(SysUser sysUser) {
        String workshopSection = sysUser.getWorkshopSection();
        List<String> workshopSectionList = null;
        if (StringUtils.isNotEmpty(workshopSection)) {
            workshopSectionList = Arrays.asList(workshopSection.split(","));
        }
        return userService.getAllUser(sysUser, workshopSectionList);
    }

    public List<String> getAllLocation() {
        return userService.getAllLocation();
    }

    public UserSalaryData getUserSalaryData(SysUser sysUser) {
        return userService.getUserSalaryData(sysUser);
    }
}
